package edu.pku.hawk.service.launcher;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.tuscany.sca.node.SCANode;
import org.apache.tuscany.sca.node.SCANodeFactory;
import org.apache.tuscany.sca.node.launcher.DomainManagerLauncher;

import edu.pku.hawk.controller.util.Constants;
import edu.pku.hawk.controller.util.Util;

public class LaunchAll {
	private static final Logger logger = Logger.getLogger(LaunchAll.class.getName());
	
	private static SCANode manager;
	private static SCANode sensorNode;
 
	
	public static void main(String[] args) throws Exception{
		 logger.info("=====Setting up domain");
		 long start = System.currentTimeMillis();
		try {
		  
           DomainManagerLauncher managerLauncher = DomainManagerLauncher.newInstance();
           manager = managerLauncher.createDomainManager();
           manager.start();
           
           SCANodeFactory nodeFactory = SCANodeFactory.newInstance();
           sensorNode  = nodeFactory.createSCANodeFromURL("http://localhost:9990/node-config/SensorDataServiceNode");
           
           sensorNode.start();
           
           //Publish service to uddi server
           String sensorServiceURI=Util.generateRMIAddress(Util.getLocalIPAddress(),"9000","SensorDataService");
           boolean success=SaveWebserviceURI.savewebserviceURI("SensorDataService",sensorServiceURI,Constants.UDDI_Server_URL);
           logger.info("=====Publish sensor service uri:"+sensorServiceURI+" to uddi :"+success);
           
 	   }catch(Exception ex){
 		  logger.log(Level.SEVERE, "SCA Domain Manager could not be started",ex);
			throw ex;
 	   }
 		long end = System.currentTimeMillis();
		logger.info("Domain started in " + (end - start) + " ms.");
		while(System.in.read() != 'q') {
		}

		try {
			if (sensorNode != null)
				sensorNode.stop();
		 
			manager.stop();
		} catch (Exception ex) {
			logger.log(Level.SEVERE, "SCA Domain Manager could not be stopped",ex);
			throw ex;
		}
 	   
  }
}
